package org.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.example.reggie.entry.Employee;
import org.example.reggie.result.ResultData;
import org.example.reggie.service.EmployeeService;
import org.example.reggie.utils.MD5Util;
import org.example.reggie.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 系统员工信息 controller控制类
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param request
     * @param employee
     * @return
     */
    @RequestMapping("/login")
    public ResultData<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        String password = employee.getPassword();
        password = MD5Util.getMD5(password);
        //配置查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        //查询
        Employee empl = employeeService.getOne(queryWrapper);
        Optional <Employee> opeml = Optional.ofNullable(empl);
        if(opeml.isPresent()){
            if(!password.equals(empl.getPassword())){
                return ResultData.error("登录失败");
            }else if(empl.getStatus() == 0){
                return ResultData.error("当前账户正在封禁");
            }else{
                request.getSession().setAttribute("employee",empl.getId());
                Map<String, Object> map  = new HashMap<>();
                map.put("id",empl.getId());
                map.put("username",empl.getUsername());
                //保存用户id与用户名到当前线程中
                ThreadLocalUtil.setMap(map);
                return  ResultData.success("登录成功",empl);
            }
        }else{
            return ResultData.error("登录失败");
        }

    }

    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public ResultData<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        ThreadLocalUtil.remove();
        return ResultData.success("退出成功",null);
    }

    /**
     *
     * @param employee
     * @return
     */
    @PostMapping("/insert")
    public ResultData<String> save(HttpServletRequest request,@RequestBody Employee employee){
        //密码默认123456，使用md5加密
        employee.setPassword(MD5Util.getMD5("123456"));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获取当前新增操作人员的id
        //Long empId= (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser((Long) ThreadLocalUtil.getMap().get("id"));
        employee.setUpdateUser((Long) ThreadLocalUtil.getMap().get("id"));
        /**
         * 插入时候可能同名，数据库中设置username为唯一性，会抛异常，可使用try{}catch(){}处理
         * 也可以使用全局异常处理，更加美观
         */

        employeeService.save(employee);
        return ResultData.success("添加成功",null);
    }

    /**
     * 员工分页查询
     * @param pageSize
     * @param pageNum
     * @param name
     * @return
     */
    @GetMapping("/page")
    public ResultData<Page> page(Integer pageNum,Integer pageSize,String name){
        //分页构造器
        Page pageInfo=new Page(pageNum,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //模糊搜索
        queryWrapper.like(StringUtils.hasLength(name),Employee::getName,name);
        //排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //查询结果自动封装到pageInfo
        employeeService.page(pageInfo,queryWrapper);
        //可以在服务端给页面响应json数据时进行处理，将long型数据统一转为String字符串
        return ResultData.success("查询成功",pageInfo);
    }

    /**
     * 修改信息
     * @param employee
     * @return
     */
    @PutMapping("/update")
    public ResultData<String> update(@RequestBody Employee employee){
        //获取登录者id
        Long id = (Long) ThreadLocalUtil.getMap().get("id");
        employee.setUpdateUser(id);
        employee.setUpdateTime(LocalDateTime.now());
        //js对long型数据处理丢失精度，导致提交过来的id与数据库的id不一致
        //可以在服务端给页面响应json数据时进行处理，将long型数据统一转为String字符串
        employeeService.updateById(employee);
        return ResultData.success("更新成功",null);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultData<Employee> getById(@PathVariable Long id){
        Employee employee= employeeService.getById(id);
        if(null !=employee ){
            return ResultData.success("查询成功",employee);
        }else {
            return ResultData.error("查询失败");
        }
    }
}
